package com.tutou.ikgroup.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tutou.ikgroup.mapper.ChatFriendMapper;
import com.tutou.ikgroup.pojo.dto.FriendDTO;
import com.tutou.ikgroup.pojo.po.Friend;
import com.tutou.ikgroup.service.UserFriend;
import com.tutou.ikgroup.util.ChangeType;
import com.tutou.ikgroup.util.UserCheck;
import com.tutou.ikgroup.websocket.ChannelContextUtil;
import com.tutou.ikuser.mapper.UserMapper;
import com.tutou.ikuser.pojo.dto.Result;
import com.tutou.ikuser.pojo.po.User;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static com.tutou.ikuser.util.RedisConstants.*;


@Service
@Slf4j
public class UserFriendImpl implements UserFriend {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChatFriendMapper chatFriendMapper;

    @Autowired
    private ChannelContextUtil channelContextUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //发送好友申请
    @Override
    public Result addFriend(String token, FriendDTO friendDTO) {
        User sender = UserCheck.token(stringRedisTemplate, token);
        friendDTO.setSenderId(sender.getUserId());
        //redis查询被添加用户是否存在
        String receiverPhone = friendDTO.getReceiverPhone();
        User receiver = UserCheck.addRedisUser(stringRedisTemplate, receiverPhone, userMapper);
        friendDTO.setReceiverId(receiver.getUserId());
        return add(sender, friendDTO);
    }

    public Result add(User sender, FriendDTO friendDTO) {
        friendDTO.setReceiverId(friendDTO.getReceiverId());
        friendDTO.setSenderName(sender.getUserName());
        //判断是否已经添加过
        String status = chatFriendMapper.getFriend(friendDTO);
        if (status == "1" || status == null) {
            if (chatFriendMapper.judgeFriendAdd(friendDTO) == 0) {
                //将好友信息请求保存到数据库
                friendDTO.setMessage(friendDTO.getSenderName() + "：" + friendDTO.getMessage());
                chatFriendMapper.saveFriend(friendDTO);
                return channelContextUtil.addFriend(friendDTO);
            }
        } else if (status == "3") {
            return Result.fail("该用户已添加~");
        }
        return channelContextUtil.addFriend(friendDTO);
    }

    //同意或拒绝好友申请
    @Override
    public Result passOrRejectFriend(String token, FriendDTO friendDTO) {
        User user = UserCheck.token(stringRedisTemplate, token);
        String senderName = user.getUserName();
        String receiverPhone = friendDTO.getReceiverPhone();
        User receiver = UserCheck.addRedisUser(stringRedisTemplate, receiverPhone, userMapper);
        //判断该好友是否已经添加
        if (chatFriendMapper.getFriend(friendDTO).equals("3")) {
            return Result.fail("该用户已经是您的好友~");
        }
        //修改好友请求状态
        chatFriendMapper.passOrRejectFriend(friendDTO);
        chatFriendMapper.passOrRejectFriend2(friendDTO);
        friendDTO.setSenderName(senderName);
        friendDTO.setReceiverName(receiver.getUserName());
        return channelContextUtil.passOrRejectFriend(friendDTO);
    }

    //获取所有好友申请列表
    @Override
    public Result getFriendRequestList(String userId) {
        List<Friend> friendAllRequest = chatFriendMapper.getFriendAllRequest(userId);
        if (friendAllRequest.size() == 0) {
            return Result.ok("没有好友请求~");
        }
        //修改好友申请列表状态，将未读设为已读
        chatFriendMapper.UpdateOfflineFriendRequestStatus();
        return Result.ok(friendAllRequest);
    }

    //好友列表
    @SneakyThrows
    @Override
    public Result getFriendList(String token) {
        //判断用户是否存在
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(token);
        User user = BeanUtil.copyProperties(userMap, User.class);
        String userId = user.getUserId();
        //从数据库找
        List<Friend> friendList = chatFriendMapper.getFriendList(userId);
        return Result.ok(friendList);
    }

    //删除好友
    @Override
    public Result deleteFriend(String token, FriendDTO friendDTO) {
        //从redis获取用户信息
        User sender = UserCheck.token(stringRedisTemplate, token);
        if (sender == null) {
            return Result.fail("身份已过期~请登录后重试~");
        }
        friendDTO.setSenderId(sender.getUserId());
        User receiver = UserCheck.addRedisUser(stringRedisTemplate, friendDTO.getReceiverPhone(), userMapper);
        friendDTO.setReceiverName(receiver.getUserName()).setReceiverId(receiver.getUserId());
        // 数据库删除好友、聊天信息
        chatFriendMapper.deleteFriend(friendDTO);
        chatFriendMapper.deleteFriendMessage(friendDTO);
        //redis删除信息
        stringRedisTemplate.delete(CHAT_OBO_KEY + sender.getUserId() + ":" + receiver.getUserId() + ":" + sender.getUserId());
        return channelContextUtil.deleteFriend(friendDTO);
    }
}
